from typing import List, Optional
from fastapi import HTTPException, Depends
from sqlalchemy.orm import Session
from app.models.item import Item, ItemCreate, ItemUpdate
from app.database.database import Database
from app.config.database import get_db
from app.config.logger import logger

class ItemService:
    def __init__(self, db: Session):
        self.db = Database(db)

    def get_all_items(self) -> List[Item]:
        logger.info("Getting all items")
        return self.db.get_all_items()

    def get_item(self, item_id: int) -> Item:
        logger.info(f"Getting item with id: {item_id}")
        item = self.db.get_item(item_id)
        if not item:
            logger.warning(f"Item not found with id: {item_id}")
            raise HTTPException(status_code=404, detail="Item not found")
        return item

    def create_item(self, item: ItemCreate) -> Item:
        logger.info(f"Creating new item: {item.dict()}")
        new_item = self.db.create_item(item)
        logger.info(f"Created item with id: {new_item.id}")
        return new_item

    def update_item(self, item_id: int, item: ItemUpdate) -> Item:
        logger.info(f"Updating item {item_id} with data: {item.dict()}")
        updated_item = self.db.update_item(item_id, item)
        if not updated_item:
            logger.warning(f"Item not found for update with id: {item_id}")
            raise HTTPException(status_code=404, detail="Item not found")
        logger.info(f"Updated item with id: {item_id}")
        return updated_item

    def delete_item(self, item_id: int) -> None:
        logger.info(f"Deleting item with id: {item_id}")
        if not self.db.delete_item(item_id):
            logger.warning(f"Item not found for deletion with id: {item_id}")
            raise HTTPException(status_code=404, detail="Item not found")
        logger.info(f"Deleted item with id: {item_id}")

def get_item_service(db: Session = Depends(get_db)) -> ItemService:
    return ItemService(db) 